package com.gitee.wsl.ext.string

import com.gitee.wsl.lang.character.xml


fun isXmlNameStart(c: Char): Boolean {
    return c != '$'
    //return c.isJavaIdentifierStart() && c != '$'.code
}


fun isXmlNamePart(c: Int): Boolean {
    if (c == '$'.code) return false

    if (Char.xml.isName(c)) {
        // 同时也是JavaIdentifierPart
        if (c == 8494 || c == 183 || c == 903 || c == 1758) return false
        return true
    } else {
        return false
    }
}

fun isValidXmlName(s: String?): Boolean {
    return isValidXmlName(s, true, true)
}


fun isValidXmlNamespaceName(s: String?): Boolean {
    return isValidXmlName(s, false, false)
}


fun isValidXmlName(s: String?, allowColon: Boolean, allowDot: Boolean): Boolean {
    if (s == null || s.length == 0) return false
    val c = s.get(0)
    // 与规范不同，这里不允许起始字符为58[：]和8494[℮]，这样一来就同时满足JavaIdentifierStart条件
    if (!isXmlNameStart(c)) return false

    return _isValidXmlNamePart(s, allowColon, allowDot)
}

fun _isValidXmlNamePart(s: String, allowColon: Boolean, allowDot: Boolean): Boolean {
    // 与规范不同，不允许连续的分割符，也不允许以分割符结尾
    var i: Int
    val n: Int
    // state =1 表示前一个字符为分隔符
    var state = 0
    i = 1
    n = s.length
    while (i < n) {
        val c = s.get(i)
        if (c == '-') {
            if (state == 1) return false
            state = 1
            i++
            continue
        }

        if (c == ':') {
            if (!allowColon) return false
            if (state == 1) return false
            state = 1
            i++
            continue
        }
        if (c == '.') {
            if (!allowDot) return false
            if (state == 1) return false
            state = 1
            i++
            continue
        }

        if (!isXmlNamePart(c.code)) return false
        state = 0
        i++
    }
    // 不允许分隔符结尾
    if (state == 1) return false
    return true
}